# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np

from scipy.sparse import hstack
from sklearn.preprocessing import StandardScaler,MinMaxScaler,MaxAbsScaler,OneHotEncoder
from sklearn.metrics import r2_score


# 先看一下Y的变化曲线，判断是否和随着日期发生变化
data = pd.read_csv('../notebook/day.csv')
categorical_features = ['season','mnth','weathersit','weekday']
data_cat = data[categorical_features]

# OneHotEnc = preprocessing.OneHotEncoder()
# data_cat = OneHotEnc.fit_transform(data_cat)
# print(data_cat)

for col in categorical_features:
    data_cat[col] = data_cat[col].astype('object')

data_cat = pd.get_dummies(data_cat)
print(data_cat.info())
print(data_cat.head())

numbic_features = ["temp", "atemp" , "hum", "windspeed"]
data_numbic = data[numbic_features]
data_numbic = MinMaxScaler().fit_transform(data_numbic)
data_numbic = pd.DataFrame(data = data_numbic , columns=numbic_features , index=data.index)
print(data_numbic.info())
print(data_numbic.head())

data_tmp = pd.concat([ data["instant"], data_cat, data_numbic, data[["holiday", "workingday", "yr", "cnt"]]], axis=1);
data_tmp.to_csv('day_preprocessed.csv', index=False)
print(">>>>>")
print(data_tmp.info())
print(data_tmp.head())

data_0 = data_tmp[data.yr == 0]
data_1 = data_tmp[data.yr == 1]

y_train = data_0['cnt'].values
y_test = data_1['cnt'].values
X_train = data_0.drop('cnt', axis = 1).drop('yr', axis = 1).drop('instant', axis = 1)
X_test = data_1.drop('cnt', axis = 1).drop('yr', axis = 1).drop('instant', axis = 1)

#对y做标准化，不是必须
ss_y = StandardScaler()
y_train = ss_y.fit_transform(y_train.reshape(-1,1))
y_test = ss_y.transform(y_test.reshape(-1,1))

#训练集和测试集y的均值差异很大，均值差异用作校正
mean_test_y = y_test.mean()
#归一化后train均值为0
#mean_train_y = 0
mean_diff = mean_test_y;
print("difference between mean of train and test y:", mean_diff)

print(">>>>>>")
print(X_train.describe())

from sklearn.linear_model import  RidgeCV

#设置超参数（正则参数）范围
alphas = [ 0.01, 0.1, 1, 10,100]
#n_alphas = 20
#alphas = np.logspace(-5,2,n_alphas)

#生成一个RidgeCV实例
ridge = RidgeCV(alphas=alphas)

#模型训练
ridge.fit(X_train, y_train)

#预测
y_test_pred_ridge = ridge.predict(X_test)
y_test_pred_ridge += mean_diff
y_train_pred_ridge = ridge.predict(X_train)


# 评估，使用r2_score评价模型在测试集和训练集上的性能
print (('The r2 score of RidgeCV on test is'), r2_score(y_test, y_test_pred_ridge))
print (('The r2 score of RidgeCV on train is'), r2_score(y_train, y_train_pred_ridge))

# print(X_test.describe())

from sklearn.linear_model import LassoCV

#设置超参数搜索范围
alphas = [ 0.01, 0.1, 1, 10]

#生成一个LassoCV实例
lasso = LassoCV(alphas = alphas)

#训练（内含CV）
lasso.fit(X_train, y_train)

#测试
y_test_pred_lasso = lasso.predict(X_test)
y_train_pred_lasso = lasso.predict(X_train)

print ('alpha is:', lasso.alpha_)
# 评估，使用r2_score评价模型在测试集和训练集上的性能
print 'The r2 score of LassoCV on test is', r2_score(y_test, y_test_pred_lasso)
print 'The r2 score of LassoCV on train is', r2_score(y_train, y_train_pred_lasso)